/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.security.rest;

import cn.hutool.core.lang.Snowflake;
import com.fzhucc.annotation.rest.AnonymousGetMapping;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.security.domain.UserCode;
import com.fzhucc.modules.security.repository.UserCodeRepository;
import com.fzhucc.modules.security.service.AuthenticationService;
import com.fzhucc.utils.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;


/**
 * @author yyg
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/auth/sso")
@Api(tags = "系统：跳转管理")
public class AuthorizationLoginController {

    private final UserCodeRepository userCodeRepository;

    //单点登录成功后 重定向地址写前段 前段拿code访问后端 后端拿到token

    @ApiOperation("市总sso登录回调接口")
    @AnonymousGetMapping(value = "/ssoLoginVerify")
    public void ssoLoginVerify(@RequestParam String ticket, @RequestParam String backUrl, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        String url = "https://ec.fzszgh.com/sso/proxyValidate";//请求验证地址

//        String service_url = "https://szszgh.fzzgsc.com/api/api/auth/ssoLoginVerify?backUrl="+ backUrl + "&ticket=" + ticket;//回调地址
//        String service_url =  URLEncoder.encode("http://192.168.3.98:14000/api/auth/ssoLoginVerify?backUrl="+ URLEncoder.encode(backUrl, "UTF-8") , "UTF-8");//回调地址
        String service_url = URLEncoder.encode("https://zqxyy.fzzgsc.com/api/api/auth/sso/ssoLoginVerify?backUrl=" + URLEncoder.encode(backUrl, "UTF-8"), "UTF-8");//回调地址


        service_url += "&ticket=" + ticket;

        String param = "service=" + service_url;
        String res = HttpUtils.sendPost(url, param);

        if (res != null && res != "") {
            if (res.contains("authenticationSuccess")) {
                String str = "<cas:user>";
                String str2 = "</cas:user>";
                String[] result = res.split(str);
                if (result != null && result.length == 2) {
                    String result2 = result[1];
                    if (result2 != null) {
                        String[] result3 = result2.split(str2);
                        if (result3 != null && result3.length == 2) {
                            String username = result3[0];
                            //不进行登录 返回code
                            UserCode resData = userCodeRepository.findByPhone(username);
                            //随机code
                            Snowflake snowflake = new Snowflake();
                            String code = snowflake.nextIdStr();
                            if (resData == null) {
                                UserCode userCode = new UserCode();
                                userCode.setCode(code);
                                userCode.setPhone(username);
                                userCodeRepository.save(userCode);
                            } else {
                                resData.setCode(code);
                                userCodeRepository.save(resData);
                            }
                            String resulturl;
                            if (backUrl.contains("?")) {
                                resulturl = backUrl + "&code=" + code;
                            } else {
                                resulturl = backUrl + "?code=" + code;
                            }

                            resp.sendRedirect(resulturl);
                        }
                    }
                }
                throw new BadRequestException("未获取到用户标识");
            } else {
                throw new BadRequestException(res);
            }
        } else {
            throw new BadRequestException("返回数据验证失败");
        }
    }

}
